from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render
from django.conf import settings
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings
from oauth.models import OAuthQQUser
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from oauth.serializers import QQAuthUserSerializer

from carts.utils import merge_cart_cookie_to_redis


class QQAuthURLView(APIView):
    def get(self, request):

        # 获取前端传来的state
        state = request.query_params.get('state', '/')

        # 生成qq对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        # 构造qq登录的跳转链接
        login_url = oauth.get_qq_url()
        # 返回结果
        return Response({'login_url': login_url})


class QQAuthUserView(CreateAPIView):

    serializer_class = QQAuthUserSerializer

    """用户扫码登录的回调处理"""
    def get(self, request):

        # 获取code值
        code = request.query_params.get('code', None)
        # 判断code值是否存在
        if not code:
            return Response({'errors': '缺少code值'}, status=400)
        # 生成qq对象
        state = '/'
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        try:
            # 通过code值向QQ服务器获取到access_token
            access_token = oauth.get_access_token(code)
            # 通过access_token向QQ服务器获取openid
            openid = oauth.get_open_id(access_token)
        except BaseException:
            return Response({'message': 'QQ服务器异常'}, status=503)
        # 判断openid是否绑定过美多用户对象
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # openid没有绑定过美多用户,返回给前端openid，方便后续进行绑定操作写入数据库
            # 对openid进行加密之后返回给前端
            tjs = TJS(settings.SECRET_KEY, 300)
            open_id = tjs.dumps({'openid': openid}).decode()
            return Response({'access_token': open_id})
        else:
            # openid绑定过美多用户
            # 登陆成功
            # 获取用户对象
            user = qq_user.user
            # 生成token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)
            return response

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, self.user, response)
        return response

    # def post(self, request):
    #     # 获取数据
    #
    #     # 校验数据
    #
    #     # 保存数据
    #
    #     # 返回结果